﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using blackhouse.BlackApart.Business.Calendar;
using blackhouse.BlackApart.Business.Apartments;

namespace blackhouse.BlackApart.Web {
    public class DisplayCalendar {

        #region Fields

        private DateTime beginDate;

        #endregion

        #region Properties

        public int LastDay { get; set; }
        public int Weeks { get; set; }
        public List<CalendarDay> Days { get; set; }

        #endregion

        #region Constructors

        public DisplayCalendar() {
            this.SetDate(DateTime.Now.Month, DateTime.Now.Year);
        }

        public DisplayCalendar(int month, int year) {
            this.SetDate(month, year);
        }

        #endregion

        #region Methods

        public void SetDate(int month, int year) {
            this.beginDate = new DateTime(year, month, 1);
            this.Weeks = 0;
            this.BuildDays();
        }

        private void BuildDays() {

            this.Days = new List<CalendarDay>(31);

            DateTime daysFromBegin = this.beginDate;
            this.LastDay = beginDate.AddMonths(1).AddDays(-1).Day;
            this.Weeks++;

            while (daysFromBegin.Month == this.beginDate.Month) {
                int dayOfWeekIndex = (int) daysFromBegin.DayOfWeek;
                dayOfWeekIndex -= 1;
                if (dayOfWeekIndex == -1) dayOfWeekIndex = 6;

                this.Days.Add(new CalendarDay(daysFromBegin, this.Weeks, dayOfWeekIndex));
                daysFromBegin = daysFromBegin.AddDays(1);
                if (dayOfWeekIndex == 6) {
                    this.Weeks++;
                }
            }
            this.Weeks = this.Days.Max(d => d.Week);
        }

        public void ApplyCalendar(ICalendar calendar, int groupId) {
            foreach (CalendarDay day in this.Days) {
                  if (calendar.GetDayState(day.AssocDate) == 0)
                    day.Type = CalendarDayType.Busy;
                if (day.Type == CalendarDayType.Free)
                    day.SetUrlToReservation(groupId);
            }
        }

        public static DateTime GetStartDate(int month, int year) {
            DateTime startDate = new DateTime(year, month, 1, 0, 0, 0);
            if (startDate < DateTime.Now)
                startDate = DateTime.Today;
            return startDate;
        }

        public static DateTime GetEndDate(DateTime startDate) {
            DateTime endDate = startDate.AddMonths(1).AddDays(-1);
            return endDate;
        }

        #endregion

    }
}